package com.tegtech.module.sms.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.tegtech.common.properties.AppProperties;
import com.tegtech.common.utils.date.DateUtils;
import com.tegtech.module.sms.log.SmsLogService;
import com.tegtech.module.sms.log.domain.SmsLog;
import com.tegtech.module.sms.service.IMessageService;
import com.tegtech.module.sms.service.ITemplate;
import com.tegtech.tools.aliyun.support.SmsMessage;

@Service
public class MessageServiceImpl implements IMessageService {
	
	@Autowired
	private SmsLogService smsLogService;

	@Override
	public void sendMessage(String phone, ITemplate template, String templateParam) {
		SendSmsResponse sendSmsResponse = SmsMessage.send(phone, template.getCode(), templateParam);
		recordLog(phone, template, templateParam, sendSmsResponse);
	}
	
	@Override
	public void sendMessage(String phone, ITemplate template) {
		sendMessage(phone, template, null);
	}

	/**
	 * 记录日志
	 * @param sendSmsResponse
	 */
	private void recordLog(String phone, ITemplate template, String templateParam, SendSmsResponse sendSmsResponse) {
		if(AppProperties.isEnableSmsLog()) {
			SmsLog smsLog = SmsLog.builder()
					.phone(phone)
					.templateCode(template.getCode())
					.content(template.getContent())
					.templateParam(templateParam)
					.resultCode(sendSmsResponse.getCode())
					.resultMessage(sendSmsResponse.getMessage())
					.createTime(DateUtils.now())
					.build();
			smsLogService.record(smsLog);
		}
	}

}
